<!--
 * @Description: 结算日报表
 * @Author: py
 * @Date: 2024-03-17
-->
<script setup lang="ts" name="settlement-daily-report">
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'

import { statementSheetExportApi, statementSheetListApi } from '@fl/api/charge-settle'
import { SearchTable } from '@fl/components'
import XEUtils from 'xe-utils'
import type { IRowV0, KeyCount, MergeCellOptions } from './types'

const oDay = day()
// const todayLabel = oDay.format('YYYY-MM-DD')
const yesterdayLabel = oDay.subtract(1, 'day').format('YYYY-MM-DD')
const initialState = {
    date: yesterdayLabel,
}

const queryState = ref({
    ...initialState,
})

const isLoading = ref(false)
const tableData = ref([])
const oGroupCount = ref<KeyCount>({})
const totalData = ref<IRowV0>({})
const unRepetData = ref<IRowV0[]>([])
const exportLoading = ref(false)
// const exportPdfLoading = ref(false)
function formatPrice({ cellValue }) {
    if (cellValue === null) {
        return ''
    }

    return cellValue === 0 ? '¥ 0' : `¥ ${Number.parseFloat(cellValue).toFixed(2)}`
}
function formatMoney(cellValue) {
    if (cellValue === null) {
        return ''
    }

    return cellValue === 0 ? '¥ 0' : `¥ ${XEUtils.commafy(Number(cellValue), { digits: 2 })}`
}

// function sumNum(list, field) {
//     let count = 0
//     list.forEach((item) => {
//         count += Number(item[field])
//     })
//     return count
// }
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { fixed: 'left', field: 'seq', title: '序号', type: 'seq', width: 60 },
        { fixed: 'left', field: 'vendorName', minWidth: 100, title: '合作方' },
        { fixed: 'left', align: 'left', field: 'stationName', minWidth: 250, title: '站点' },
        {
            title: '营业额',
            children: [
                { align: 'right', field: 'revenue', formatter: formatPrice, title: '单日', width: 120 },
                { align: 'right', field: 'monthRevenue', formatter: formatPrice, title: '本月累计', width: 120 },
            ],
        },
        {
            title: '资金流入',
            children: [
                { align: 'right', field: 'capitalInflow', formatter: formatPrice, title: '单日', width: 120 },
                { align: 'right', field: 'monthCapitalInflow', formatter: formatPrice, title: '本月累计', width: 120 },
            ],
        },
        {
            title: '佣金',
            children: [
                { align: 'right', field: 'commission', formatter: formatPrice, title: '单日', width: 120 },
                { align: 'right', field: 'monthCommission', formatter: formatPrice, title: '本月累计', width: 120 },
            ],
        },
        {
            title: '资金流出',
            children: [
                { align: 'right', field: 'capitalOutflow', formatter: formatPrice, title: '单日', width: 120 },
                { align: 'right', field: 'monthCapitalOutflow', formatter: formatPrice, title: '本月累计', width: 120 },
            ],
        },
        {
            title: '实收电费',
            children: [
                { align: 'right', field: 'actualChargeFee', formatter: formatPrice, title: '单日', width: 120 },
                { align: 'right', field: 'monthActualChargeFee', formatter: formatPrice, title: '本月累计', width: 120 },
            ],
        },
        {
            title: '实收服务费',
            children: [
                { align: 'right', field: 'actualServiceFee', formatter: formatPrice, title: '单日', width: 120 },
                { align: 'right', field: 'monthActualServiceFee', formatter: formatPrice, title: '本月累计', width: 120 },
            ],
        },
        {
            title: '小桔平台技术服务费',
            children: [
                { align: 'right', field: 'platformServiceFee', formatter: formatPrice, title: '单日', width: 120 },
                { align: 'right', field: 'monthPlatformServiceFee', formatter: formatPrice, title: '本月累计', width: 120 },
            ],
        },
        {
            title: '停车费申诉扣减费',
            children: [
                { align: 'right', field: 'parkingFee', formatter: formatPrice, title: '单日', width: 120 },
                { align: 'right', field: 'monthParkingFee', formatter: formatPrice, title: '本月累计', width: 120 },
            ],
        },
    ],
    footerAlign: 'right',
    footerData: [
        {
            seq: '合计',
            vendorName: computed(() => totalData.value.vendorName),
            stationName: computed(() => totalData.value.stationName),
            revenue: computed(() => formatMoney(totalData.value.revenue)),
            monthRevenue: computed(() => formatMoney(totalData.value.monthRevenue)),
            capitalInflow: computed(() => formatMoney(totalData.value.capitalInflow)),
            monthCapitalInflow: computed(() => formatMoney(totalData.value.monthCapitalInflow)),
            commission: computed(() => formatMoney(totalData.value.commission)),
            monthCommission: computed(() => formatMoney(totalData.value.monthCommission)),
            capitalOutflow: computed(() => formatMoney(totalData.value.capitalOutflow)),
            monthCapitalOutflow: computed(() => formatMoney(totalData.value.monthCapitalOutflow)),
            actualChargeFee: computed(() => formatMoney(totalData.value.actualChargeFee)),
            monthActualChargeFee: computed(() => formatMoney(totalData.value.monthActualChargeFee)),
            actualServiceFee: computed(() => formatMoney(totalData.value.actualServiceFee)),
            monthActualServiceFee: computed(() => formatMoney(totalData.value.monthActualServiceFee)),
            platformServiceFee: computed(() => formatMoney(totalData.value.platformServiceFee)),
            monthPlatformServiceFee: computed(() => formatMoney(totalData.value.monthPlatformServiceFee)),
            parkingFee: computed(() => formatMoney(totalData.value.parkingFee)),
            monthParkingFee: computed(() => formatMoney(totalData.value.monthParkingFee)),
        },
    ],
    // footerMethod({ columns }) {
    //     return [
    //         columns.map((column, columnIndex) => {
    //             if (columnIndex === 0) {
    //                 return '合计'
    //             }
    //             if (columnIndex > 2) {
    //                 // return sumNum(data, column.field)
    //                 if (totalData.value.length === 0)
    //                     return ''
    //                 const cellValue = totalData.value[0][column.field]
    //                 return cellValue === null || cellValue === 0 ? '¥ 0' : `¥ ${XEUtils.commafy(Number(cellValue), { digits: 2 })}`
    //             }
    //             return ''
    //         }),
    //     ]
    // },
    footerCellClassName: 'table-footer-cell',
    footerRowClassName: 'bg-#fff7e8',
    maxHeight: 370,
    mergeCells: [],
    mergeFooterItems: [],
    rowConfig: {
        // isHover: true,
        keyField: 'id',
    },
    seqConfig: {
        seqMethod({ row }) {
            const targetIndex = unRepetData.value.findIndex(item => item.vendorId === row.vendorId)
            if (targetIndex === -1) {
                return ''
            }
            return targetIndex + 1
        },
    },
    // spanMethod: ({ row, column, _rowIndex, visibleData }) => {
    //     const fields = ['vendorId']
    //     const cellValue = row[column.field]
    //     if (cellValue && fields.includes(column.field)) {
    //         const prevRow = visibleData[_rowIndex - 1]
    //         let nextRow = visibleData[_rowIndex + 1]
    //         if (prevRow && prevRow[column.field] === cellValue) {
    //             return { rowspan: 0, colspan: 0 }
    //         }
    //         else {
    //             let countRowspan = 1
    //             while (nextRow && nextRow[column.field] === cellValue) {
    //                 nextRow = visibleData[++countRowspan + _rowIndex]
    //             }
    //             if (countRowspan > 1) {
    //                 return { rowspan: countRowspan, colspan: 1 }
    //             }
    //         }
    //     }
    // },
    showFooter: true,
    showOverflow: false,
    stripe: false,
})

const tablePage = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0,
})

function getList() {
    isLoading.value = true

    const oParams = {
        // pageNum: tablePage.value.currentPage,
        // pageSize: tablePage.value.pageSize,
        ...queryState.value,
    }
    statementSheetListApi(oParams).then((res) => {
        // const { records, total } = res
        // tablePage.value.total = +total
        if (res.length) {
            tableData.value = res.slice(0, -1)
            unRepetData.value = XEUtils.uniq(tableData.value, 'vendorId')
            oGroupCount.value = XEUtils.countBy(tableData.value, 'vendorId')
            totalData.value = res.at(-1)

            let rCount = 0
            gridOptions.mergeCells = Object.entries(oGroupCount.value).reduce((pre, cur, index, arr) => {
                const [, value] = cur
                if (index === 0) {
                    pre.push(
                        { row: 0, col: 0, rowspan: value, colspan: 1 },
                        { row: 0, col: 1, rowspan: value, colspan: 1 },
                    )
                }
                else {
                    rCount += arr[index - 1][1]
                    pre.push(
                        { row: rCount, col: 0, rowspan: value, colspan: 1 },
                        { row: rCount, col: 1, rowspan: value, colspan: 1 },
                    )
                }
                return pre
            }, [] as MergeCellOptions[])

            gridOptions.mergeFooterItems = [{ row: 0, col: 0, rowspan: 1, colspan: 3 }] as MergeCellOptions[]
            gridOptions.showFooter = true
        }
        else {
            tableData.value = []
            unRepetData.value = []
            oGroupCount.value = {}
            totalData.value = []
            gridOptions.mergeCells = []
            gridOptions.showFooter = false
        }
    }).finally(() => {
        isLoading.value = false
    })
}
getList()

function handleSearch() {
    tablePage.value.currentPage = 1
    getList()
}
function handleReset() {
    queryState.value = {
        ...initialState,
    }
    tablePage.value.currentPage = 1
    tablePage.value.pageSize = 10
    getList()
}

// const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
//     tablePage.value.currentPage = currentPage
//     tablePage.value.pageSize = pageSize
//     getList()
// }

function handleExportExcel() {
    exportLoading.value = true
    statementSheetExportApi({ ...queryState.value }).then((res) => {
        const objectUrl = URL.createObjectURL(res)
        location.href = objectUrl
        URL.revokeObjectURL(objectUrl)
    }).finally(() => {
        exportLoading.value = false
    })
}
// function handleExportPdf() {
//     exportPdfLoading.value = true
//     statementPdfExportApi({ ...queryState.value }).then((res) => {
//         const objectUrl = URL.createObjectURL(res)
//         location.href = objectUrl
//         URL.revokeObjectURL(objectUrl)
//     }).finally(() => {
//         exportPdfLoading.value = false
//     })
// }
</script>

<template>
    <ElCard shadow="never"
            class="mb-20 border-none"
    >
        <el-form inline
                 class="search-form"
                 :model="queryState"
        >
            <el-form-item label="结算日期">
                <el-date-picker v-model="queryState.date"
                                type="date"
                                placeholder="请选择"
                                value-format="YYYY-MM-DD"
                                style="width: 100%"
                                :clearable="false"
                                :editable="false"
                />
            </el-form-item>

            <el-form-item class="search-btns">
                <el-button type="primary"
                           @click="handleSearch"
                >
                    搜索
                </el-button>

                <el-button @click="handleReset">
                    重置
                </el-button>
            </el-form-item>
        </el-form>
    </ElCard>

    <ElCard shadow="never"
            class="border-none"
    >
        <!-- v-model:pager="tablePage"
        @page-change="handlePageChange" -->
        <SearchTable v-bind="gridOptions"
                     :loading="isLoading"
                     :data="tableData"
        >
            <template #toolbar_buttons>
                <el-button type="primary"
                           class="mb-10"
                           :loading="exportLoading"
                           @click="handleExportExcel"
                >
                    <span class="vxe-icon-download mr-4" />

                    <span class="lh-16">导出</span>
                </el-button>

                <!-- <el-button type="primary"
                           class="mb-10"
                           :loading="exportPdfLoading"
                           @click="handleExportPdf"
                >
                    <span class="vxe-icon-download mr-4" />

                    <span class="lh-16">导出PDF</span>
                </el-button> -->
            </template>
        </SearchTable>
    </ElCard>
</template>

<style lang="less" scoped>
@import '../custom.less';

.search-form {
    :deep(.el-form-item) {
        width: 300px;
        margin-right: 20px;
        margin-bottom: 0;

        &.search-btns {
            width: auto;
            margin-right: 0;
        }
    }
}

:deep(.vxe-body--row) {
    &:nth-child(even) {
        background: inherit;
    }
}

:deep(.table-footer-cell) {
    font-weight: 500;
}
</style>
